<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="./dist/html2canvas.js"></script>
    <script src="./dist/jspdf.js"></script>
    <script src="./dist/moment.js"></script>
    <title>乙供材接收单</title>
    <style>
        @media print {

            /* 设置横向打印 */
            @page {
                size: A3;
                /* 设置页面方向为横向 */
            }

            /* 设置纵向打印 */
            /* @page {
        size: portrait; // 设置页面方向为纵向
      } */
        }

        body {
            background-color: #fff;
            padding: 32px;
        }

        .box {
            width: 80%;
            padding: 36px;
            background-color: #fff;
            /* width: 1121px; */
            margin: 0 auto;
            background: url(./dist/final.png) center;
        }

        /* .box{width: 1121px;height: 793px;} */
        .title {
            text-align: center;
            font-size: 20px;
            font-weight: bold;
            padding-bottom: 18px;
            border-bottom: 1px solid #000000;
        }

        .top {
            font-size: 18px;
            margin-bottom: 50px;
        }

        .flex {
            display: flex;
            align-items: center;
            justify-content: space-between;
        }

        table {
            border-collapse: collapse;
            width: 100%;
            margin-top: 20px;
        }

        th,
        td {
            border: 1px solid #000;
            padding: 10px;
            font-size: 12px;
            text-align: center;
            color: #333;
        }

        td p {
            text-align: start;
            padding-left: 18px;
            margin: 2px 0;
        }

        .bottom {
            position: relative;
            display: flex;
            justify-content: space-around;
            margin-top: 32px;
            font-weight: bold;
            font-size: 14px;
        }

        .bottom .zhang {
            position: absolute;
            top: -142px;
            left: 23%;
            margin-left: -15px;
            width: 180px;
            height: 180px;
            background: url(./dist/zhang.png) center no-repeat;
        }

        .Approval-info .title {
            text-align: start;
            font-size: 20px;
            border-bottom: 1px solid #e5e5e5;
            padding-bottom: 4px;
            margin-top: 6px;
        }

        ul {
            display: flex;
            flex-wrap: wrap;
            margin: 8px 0 -22px 0 !important;
        }

        ul,
        li {
            list-style: none;
            padding: 0;
            margin: 0;
            color: #333;
        }

        #dynamicContent {
            display: flex;
            flex-wrap: wrap;
        }

        #dynamicContent li {
            width: 30%;
            margin: 5px;
        }

        .Approval-record .title {
            font-size: 14px;
            font-weight: bold;
            padding-bottom: 0;
            border-bottom: 0;
            margin-top: 10px;
            margin-bottom: -12px;
        }

        #exportButton {
            margin: 10px;
            padding: 8px 16px;
            background-color: #007bff;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            position: absolute;
            top: 24px;
            right: 24px;
        }

        #exportButton:hover {
            background-color: #0056b3;
        }
    </style>
</head>

<body>
    <div class="box" id="content">
        <div class="title">(上市)昆明分公司 采购接收与到货验收单 - CGRKKM21012775</div>
        <div id="dynamicContent">
            <!-- Dynamic content will be rendered here -->
        </div>
        <div id="table-container"></div>
        <!-- 审批信息 -->
        <div class="Approval-record" id="Approval-record">
            <div class="title">审批记录</div>
        </div>
        <div class="bottom flex">
            <span class="buyer">采购员：<span></span></span>
            <span class="prepared">制单人：<span></span></span>
            <span class="recipient-kind">实物接收人：<span></span></span>
            <span class="Material">订单接收人（料账员）：<span></span></span>
        </div>
        <div class="bottom"><span>收货方盖章</span><span>供应商盖章</span>
            <div class="bottom zhang"></div>
        </div>
    </div>
    <button id="exportButton">导出</button>
    <script>
        // 获取要导出的HTML元素
        const element = document.getElementById('content')

        const pdf = new jsPDF()
        // 使用 html2pdf 将 HTML 元素导出为 PDF
        exportButton.addEventListener('click', () => {
            let oldStr = window.document.body.innerHTML
            let newStr = element.innerHTML
            window.document.body.innerHTML = newStr
            window.document.title = `乙供材接收单`
            window.print()
            window.document.body.innerHTML = oldStr
            return
            html2canvas(element, {
                allowTaint: true,
                useCORS: true,
                background: '#fff',
            }).then(canvas => {
                // eslint-disable-next-line new-cap
                var pdf = new jsPDF('l', 'mm', 'a3') // A3纸，横向
                // var pdf = new jsPDF('p', 'mm', 'a4') // A4纸，纵向
                var ctx = canvas.getContext('2d')
                // var a4w = 190; var a4h = 277 // A4大小，210mm x 297mm，四边各保留10mm的边距，显示区域190x277
                var a4w = 259; var a4h = 400 // A3大小，279mm x 420mm，四边各保留10mm的边距，显示区域259x400
                // var imgHeight = Math.floor(a4h * canvas.width / a4w) // 按A4显示比例换算一页图像的像素高度[这个计算方式应该是纵向]
                var imgHeight = Math.floor(a4w * canvas.width / a4h) // 按A4显示比例换算一页图像的像素高度[这个是横向打印的计算方法]
                var renderedHeight = 0
                while (renderedHeight < canvas.height) {
                    var page = document.createElement('canvas')
                    page.width = canvas.width
                    page.height = Math.min(imgHeight, canvas.height - renderedHeight)// 可能内容不足一页
                    page.getContext('2d').putImageData(ctx.getImageData(0, renderedHeight, canvas.width, Math.min(imgHeight, canvas.height - renderedHeight)), 0, 0)
                    // pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 10, a4w, Math.min(a4h, a4w * page.height / page.width)) // 添加图像到页面，保留10mm边距 [a4使用]
                    pdf.addImage(page.toDataURL('image/jpeg', 1.0), 'JPEG', 10, 10, a4w * 1.414, Math.min(a4h, a4w * page.height / page.width) * 1.414) // 添加图像到页面，保留10mm边距[a3使用1.414换算比例]
                    renderedHeight += imgHeight
                    console.log('imgHeight', imgHeight)
                    console.log('renderedHeight', renderedHeight)
                    console.log('canvas.height', canvas.height)
                    if (renderedHeight < canvas.height) {
                        pdf.addPage()// 如果后面还有内容，添加一个空页
                    }
                    // delete page;
                }
                // 保存文件
                pdf.save('乙供材接收单.pdf')
            })
        })
    </script>
    <script>
        var info = {
            buyer: "戴宣鸿", // 采购订单编号
            prepared: "董俊", // 申请单号
            recipient_kind: "董俊 15877901197", // 申请单号
            Material: "董俊 15877901197" // 订单接收人
        }

        // 用于动态填充用户信息的函数
        function fillUserInfo() {
            document.querySelector('.buyer span').innerText = info.buyer || ''
            document.querySelector('.prepared span').innerText = info.prepared || ''
            document.querySelector('.recipient-kind span').innerText = info.recipient_kind || ''
            document.querySelector('.Material span').innerText = info.Material || ''
        }
        // 上面表格数据
        var dataArray = [
            { title: '接收单号', dataIndex: 'receivingOrderNo' },
            { title: '单据说明', dataIndex: 'orderDescription' },
            { title: '打印日期', dataIndex: 'printDate' },
            { title: '供应链订单号', dataIndex: 'supplyChainOrderNo' },
            { title: 'ERP订单编号', dataIndex: 'erpOrderNo' },
            { title: '接收日期', dataIndex: 'receiveDate' },
            { title: '库存组织', dataIndex: 'inventoryOrg' },
            { title: '供应商', dataIndex: 'supplier' },
            { title: '实物签收日期', dataIndex: 'physicalReceiveDate' },
            { title: '仓库名称', dataIndex: 'warehouseName' },
            { title: '订单主体', dataIndex: 'orderSubject' },
            { title: '物资类型', dataIndex: 'materialType' },
            { title: '合同编码', dataIndex: 'contractCode' },
            { title: '未税金额(元)', dataIndex: 'untaxedAmount' },
            { title: '税金(元)', dataIndex: 'taxAmount' },
            { title: '含税金额(元)', dataIndex: 'taxIncludedAmount' }
        ]
        function renderData(dataArray) {
            var dynamicContent = document.getElementById('dynamicContent')
            var html = '<ul>'
            dataArray.forEach(function (item) {
                html += '<li><strong>' + item.title + ':</strong> ' + (item.title.indexOf('日期') > -1 ? moment(info[item.dataIndex]).format('YYYY-MM-DD') : info[item.dataIndex]) + '</li>'
            })
            html += '</ul>'
            dynamicContent.innerHTML = html
        }

        function fillPaymentTable(tableName, data, headers, isNeedTotal) {
            // 模拟数据
            var data = data

            // 获取表格容器
            var tableContainer = document.getElementById(tableName)

            // 创建表格元素
            var table = document.createElement('table')
            table.setAttribute('border', '1')

            // 创建表头
            var thead = document.createElement('thead')
            var headerRow = document.createElement('tr')
            var headers = headers

            for (var i = 0; i < headers.length; i++) {
                var th = document.createElement('th')
                th.appendChild(document.createTextNode(headers[i]))
                headerRow.appendChild(th)
            }

            thead.appendChild(headerRow)
            table.appendChild(thead)
            if (data.length === 0) {
                // 数据为空时显示无记录消息
                var noRecordRow = document.createElement('tr')
                var noRecordCell = document.createElement('td')
                noRecordCell.setAttribute('colspan', headers.length)
                noRecordCell.appendChild(document.createTextNode('无记录!'))
                noRecordRow.appendChild(noRecordCell)

                var tbody = document.createElement('tbody')
                tbody.appendChild(noRecordRow)
                table.appendChild(tbody)
            } else {
                // 创建表格内容
                var tbody = document.createElement('tbody')

                for (var i = 0; i < data.length; i++) {
                    var row = document.createElement('tr')

                    for (var key in data[i]) {
                        var cell = document.createElement('td')
                        if (key == 'materialCode') {
                            cell.appendChild(document.createTextNode(data[i]['materialCode'] + ' | ' + data[i]['materialDescription']))
                            delete data[i]['materialDescription']
                        } else {
                            cell.appendChild(document.createTextNode(data[i][key]))
                        }
                        row.appendChild(cell)
                    }

                    tbody.appendChild(row)
                }

                if (isNeedTotal) {
                    // 添加合计行
                    var totalRow = document.createElement('tr')
                    var emptyColumns = Object.keys(data[0]).map(function () { return '' })

                    // 设置“合计”文本
                    emptyColumns[0] = '合计'

                    // 计算“不含税总价”和“含税总价”列的合计
                    var totalPriceExclTaxSum = data.reduce(function (sum, item) {
                        return sum + parseFloat(item.total_price_excl_tax || 0)
                    }, 0)
                    emptyColumns[10] = totalPriceExclTaxSum.toFixed(2)

                    var totalPriceInclTaxSum = data.reduce(function (sum, item) {
                        return sum + parseFloat(item.total_price_incl_tax || 0)
                    }, 0)
                    emptyColumns[14] = totalPriceInclTaxSum.toFixed(2)

                    // 创建合计行
                    emptyColumns.forEach(function (value) {
                        var cell = document.createElement('td')
                        cell.appendChild(document.createTextNode(value))
                        totalRow.appendChild(cell)
                    })

                    tbody.appendChild(totalRow)
                }

                table.appendChild(tbody)
            }

            // 将表格添加到容器中
            tableContainer.appendChild(table)
        }
        let data = [
            { id: "1", materialCode: "10075385", materialDescription: '走线槽辅件弯槽120', supplierProductName: "弯头", unit: "套", unitCost: "12", quantity: "1", untaxedAmount: "12", taxCode: "VAT13", subInventory: "E001", projectCode: "C20304689000017", receivedQuantity: "1", actualArrivalTime: "2021-01-19" },
            { id: "2", materialCode: "10075385", materialDescription: '走线槽辅件弯槽120', supplierProductName: "弯头", unit: "套", unitCost: "12", quantity: "1", untaxedAmount: "12", taxCode: "VAT13", subInventory: "E001", projectCode: "C20304689000017", receivedQuantity: "1", actualArrivalTime: "2021-01-19" },
            { id: "3", materialCode: "10075385", materialDescription: '走线槽辅件弯槽120', supplierProductName: "弯头", unit: "套", unitCost: "12", quantity: "1", untaxedAmount: "12", taxCode: "VAT13", subInventory: "E001", projectCode: "C20304689000017", receivedQuantity: "1", actualArrivalTime: "2021-01-19" },
            { id: "4", materialCode: "10075385", materialDescription: '走线槽辅件弯槽120', supplierProductName: "弯头", unit: "套", unitCost: "12", quantity: "1", untaxedAmount: "12", taxCode: "VAT13", subInventory: "E001", projectCode: "C20304689000017", receivedQuantity: "1", actualArrivalTime: "2021-01-19" }
            // ... 可以继续添加更多的模拟数据
        ]
        let headers = ["行号", "物料编码|物料说明", "供应商产品名称", "单位", "单位成本", "数量", "未税金额(元)", "税码", "子库", "工程项目编号", "签收数量", "实际到货时间"]
        let recordData = [
            { id: "1", processStep: "处理环节", processor: '处理人', processTime: "处理时间", processComments: "处理意见" },
            { id: "1", processStep: "处理环节", processor: '处理人', processTime: "处理时间", processComments: "处理意见" },
            { id: "1", processStep: "处理环节", processor: '处理人', processTime: "处理时间", processComments: "处理意见" },
            { id: "1", processStep: "处理环节", processor: '处理人', processTime: "处理时间", processComments: "处理意见" }
            // ... 可以继续添加更多的模拟数据
        ]
        let recordHeaders = ["序号", "处理环节", "处理人", "处理时间", "处理意见"]
        window.onload = function () {
            var queryString = window.location.search
            var urlParams = new URLSearchParams(queryString)
            var id = urlParams.get('id')
            fetch('http://api.ynjov.com:8080/api/getReceivingOrderDetail/' + id)
                .then(response => {
                    
                    if (!response.ok) {
                        throw new Error('Network response was not ok')
                    }
                    return response.json()
                })
                .then(({ data: res, items, address }) => {
                    info = res
                    data = items.map((item, index) => {
                        delete item.id
                        delete item.createdAt
                        delete item.updatedAt
                        delete item.receivingOrderId
                        return {
                            index: index + 1,
                            ...item,
                            actualArrivalTime: moment(item.actualArrivalTime).format('YYYY-MM-DD')

                        }
                    })
                    recordData = address.map((item, index) => {
                        delete item.id
                        delete item.createdAt
                        delete item.updatedAt
                        delete item.receivingOrderId
                        return {
                            index: index + 1,
                            ...item,
                            processTime: moment(item.processTime).format('YYYY-MM-DD')
                        }
                    })
                    fillUserInfo()
                    fillPaymentTable('table-container', data, headers)
                    fillPaymentTable('Approval-record', recordData, recordHeaders)
                    renderData(dataArray)
                })
                .catch(error => {
                    console.error('Fetch error:', error)
                })
        };
    </script>
</body>

</html>